<?php
/**
 * Class for working with images
 *
 */
class Db_Image extends Db_Table
{
    /**
     * Object type. Match folder name with images
     *
     * @var string
     */
    var $_type = 'product'; //object type

    /**
     * Constructor
     *
     * @param string $type object type
     * @return Db_Image
     */
    function Db_Image($type='product')
    {
        parent::Db_Table('images');
        $this->_type = $type;
    }

    /**
     * Performs insert to image table. Adds last position
     *
     * @param array $data data to insert
     * @return bool operation result
     */
    function insert($data)
    {
        $sql = 'SELECT MAX(pos) FROM ' . $this->table
             . ' WHERE object_type = "' . $this->_type . '"'
             . ' AND object_id = ' . intVal($data['object_id']);

        $data['pos']         = $this->db->getField($sql) + 1;
        $data['object_type'] = $this->_type;
        return parent::insert($data);
    }

    /**
     * Delete image from database.
     * Update image positions
     * Remove image files
     *
     * @param int $id image Id
     */
    function delete($id)
    {
        //find info
        $image = $this->find($id);
        if (!$image)
            return false;
        $image = $this->makeImageInfo($image);
        //delete db row
        $result = parent::delete($id);
        if (!$result)
            return false;

        //update positions
        $sql = 'UPDATE ' . $this->table . ' SET pos = pos-1 '
             . ' WHERE object_type="' . $this->_type . '" '
             . ' AND object_id="' . $image['object_id'] . '" AND pos > ' . $image['pos'];
        $this->db->query($sql);

        //remove files
        clearstatcache();
        foreach ($image as $k => $v)
            if (false !== strpos($k, 'path') && file_exists($v))
                unlink($v);
        return true;
    }

    /**
     * Complete image info
     * with usefull data
     *
     * @param array $info image info
     * @return array updated image info
     */
    function makeImageInfo($info)
    {
        $cfg = _cfg('image.' . $this->_type);
        // use this hack for empty row
        if (!$info)
        {
            $info = $this->getNew();
            $info['id']      = '0';
            $info['mime']    = 'gif';
            $info['w']       = $cfg['min_w'];
            $info['h']       = $cfg['min_h'];
        }

        // for original image
        $info['url'] = $cfg['url'] . $this->_type . '/' . $info['id'] .  '.' . $info['mime'];
        $info['path'] = $cfg['path'] . $this->_type . '/' . $info['id'] . '.' . $info['mime'];

        // for all thumbnails if any
        foreach ($cfg['thumbs'] as $prefix => $data)
        {
            //dimensions
            $info[$prefix . 'w'] = $data['w'];
            $info[$prefix . 'h'] = $data['h'];
            //urls
            $info[$prefix . 'url'] = $cfg['url'] . $this->_type . '/' . $info['id'] . $prefix . '.' . $info['mime'];
            //path
            $info[$prefix . 'path'] = $cfg['path'] . $this->_type . '/' . $info['id'] . $prefix . '.' . $info['mime'];
        }
        return $info;
    }

    /**
     * Find object images
     *
     * @param int $id Object id
     * @return array Array of images info
     */
    function getImages($id)
    {
        $sql = 'SELECT * FROM ' . _t('images')
            . ' WHERE object_type = "'.$this->_type.'"'
            . ' AND object_id = ' . $id
            . ' ORDER BY pos';

        $rows = $this->db->getRows($sql);
        for ($i=0; $i < count($rows); $i++)
            $rows[$i] = $this->makeImageInfo($rows[$i]);

        return $rows;
    }


    /**
    * Update object images position
    *
    * @param array $position Array of photos position
    * @return bool operation result
    */
    function updatePos($position)
    {
        //check
        $values = array_values($position);
        if (count($values) != count(array_unique($values)))
        {
            return false;
        }

        //update if check was successful
        foreach ($position as $id => $pos)
        {
            $sql = 'UPDATE '.$this->table
                 . ' SET pos = ' . $pos
                 . ' WHERE id = ' . $id;
            $this->db->query($sql);
        }

        return true;
    }

   /**
    * Get first object photo
    *
    * @param int $id Object Id
    * @return array Image info
    */
    function getFirstImage($id)
    {
        $sql = 'SELECT * FROM ' . $this->table
             . ' WHERE object_type = "'.$this->_type.'"'
             . ' AND object_id = ' . intVal($id)
             . ' AND pos = 1';
        $row = $this->db->getRow($sql);

        $row = $this->makeImageInfo($row);

        return $row;
    }
}
?>